import os
from datetime import datetime
import re


def generate_markdown(fault_name, analysis_content, execution_result, script_content=None):
    """生成Markdown报告，完善执行结果提取和展示"""
    # 定义需要提取的内容区块标签
    tags = [
        r'\[\s*分析报告\s*\]',
        r'\[\s*解决方案1\s*\]',
        r'\[\s*方案1代码\s*\]',
        r'\[\s*解决方案2\s*\]',
        r'\[\s*方案2代码\s*\]',
        r'\[\s*AnalysisReport\s*\]',
        r'\[\s*Solution1\s*\]',
        r'\[\s*Code1\s*\]',
        r'\[\s*Solution2\s*\]',
        r'\[\s*Code2\s*\]'
    ]
    pattern = re.compile('|'.join(tags))
    tag_matches = list(pattern.finditer(analysis_content))

    # 处理无标签的异常情况
    if not tag_matches:
        return f"# 故障分析报告 - {fault_name}\n\n原始内容：\n{analysis_content}"

    # 分割内容为标签和文本部分
    content_parts = []
    prev_end = 0
    for match in tag_matches:
        tag_start = match.start()
        tag_end = match.end()
        content_before = analysis_content[prev_end:tag_start].strip()
        tag_text = match.group().strip()
        if content_before:
            content_parts.append(('text', content_before))
        content_parts.append(('tag', tag_text))
        prev_end = tag_end
    remaining_content = analysis_content[prev_end:].strip()
    if remaining_content:
        content_parts.append(('text', remaining_content))

    # 构建Markdown内容
    md = f"# 故障分析报告 - {fault_name}\n\n"
    current_section = None
    solution1_code_processed = False

    for part_type, content in content_parts:
        if part_type == 'tag':
            current_section = content
        else:
            if not content:
                continue

            # 统一处理中英文标签
            if current_section in ['[分析报告]', '[AnalysisReport]']:
                md += "## 一、分析报告\n"
                md += content + "\n\n"

            elif current_section in ['[解决方案1]', '[Solution1]']:
                md += "## 二、解决方案\n### 方案1\n"
                md += content + "\n\n"

            elif current_section in ['[方案1代码]', '[Code1]']:
                md += "#### 方案1执行代码\n"
                if script_content and not solution1_code_processed:
                    cleaned_code = re.sub(r'^```(?:bash)?\s*', '', script_content, flags=re.MULTILINE)
                    cleaned_code = re.sub(r'^#!/bin/bash\s*', '', cleaned_code, flags=re.MULTILINE)
                    md += "```bash\n"
                    md += cleaned_code.strip() + "\n"
                    solution1_code_processed = True
                else:
                    cleaned_code = re.sub(r'^```(?:bash)?\s*', '', content, flags=re.MULTILINE)
                    cleaned_code = re.sub(r'^#!/bin/bash\s*', '', cleaned_code, flags=re.MULTILINE)
                    md += "```bash\n"
                    md += cleaned_code.strip() + "\n"
                md += "```\n\n"

            elif current_section in ['[解决方案2]', '[Solution2]']:
                md += "### 方案2\n"
                md += content + "\n\n"

            elif current_section in ['[方案2代码]', '[Code2]']:
                md += "#### 方案2执行代码\n"
                cleaned_code = re.sub(r'^```(?:bash)?\s*', '', content, flags=re.MULTILINE)
                cleaned_code = re.sub(r'^#!/bin/bash\s*', '', cleaned_code, flags=re.MULTILINE)
                md += "```bash\n"
                md += cleaned_code.strip() + "\n"
                md += "```\n\n"

            else:
                md += content + "\n\n"

    # 执行结果展示
    md += "## 三、执行结果详情\n"
    if not execution_result:
        md += "> 未执行任何脚本或未获取到执行结果\n\n"
    else:
        # 提取执行状态
        if "✅" in execution_result:
            md += "### 执行状态：成功\n"
        elif "❌" in execution_result:
            md += "### 执行状态：失败\n"
        else:
            md += "### 执行状态：未知\n"

        # 提取退出码
        exit_code_match = re.search(r'退出码：(\d+)', execution_result)
        if exit_code_match:
            md += f"### 退出码：{exit_code_match.group(1)}\n"

        # 提取执行位置
        if "本地执行" in execution_result:
            md += "### 执行位置：本地主机\n"
        elif "目标主机" in execution_result:
            host_match = re.search(r'目标主机：(.*?)[ ：]', execution_result)
            if host_match:
                md += f"### 执行位置：远程主机 {host_match.group(1)}\n"

        # 提取详细日志
        md += "### 执行日志：\n"
        # 清理状态标记，保留原始日志
        cleaned_log = re.sub(r'[✅❌]', '', execution_result).strip()
        # 限制日志长度，避免报告过大
        if len(cleaned_log) > 1000:
            cleaned_log = cleaned_log[:1000] + "..."
        md += f"> {cleaned_log}\n\n"

    md += "\n---\n> 本报告由系统自动生成，生成时间："
    md += datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    return md


def save_markdown(md_content, output_path=None):
    """保存Markdown报告到指定路径，默认为项目根目录下的backend/data/rootheal_data"""
    if output_path is None:
        # 参考mysql/main.py的路径计算方式，使用已存在的相对路径
        current_dir = os.path.dirname(__file__)  # backend/core/roothealer
        project_root = os.path.join(current_dir, '..', '..', '..')  # 回到项目根目录 (向上3级)
        output_path = os.path.join(project_root, 'backend', 'data', 'rootheal_data')

    try:
        title_part = md_content.split('# ')[1].split('\n')[0].split(' - ')[-1]
        safe_title = re.sub(r'[^\w\-]', '_', title_part)
    except IndexError:
        safe_title = "unknown_fault"

    filename = os.path.join(
        output_path, 
        f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{safe_title}.md"
    )

    try:
        with open(filename, "w", encoding="utf-8") as f:
            f.write(md_content)
        print(f"✅ Markdown报告已保存至: {filename}")
        return filename
    except Exception as e:
        print(f"❌ 保存Markdown报告失败: {str(e)}")
        return None